<template>
  <div class="">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 提示 -->
       <el-alert
        title="商品填加"
        :closable = "false"
        type="info"
        center
        show-icon>
      </el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- Tab标签栏 -->
      <!-- tab-click 被选中的时候触发-->
      <el-form :model="addForm" :rules="addFormRrules" label-position="top" ref="addFormRef" label-width="100px" class="demo-ruleForm">
        <el-tabs @tab-click="tableClicked" :before-leave ="beforeLeave" :tab-position="'left'" v-model="activeIndex" >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item prop="goods_name" label="商品名称">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item prop="goods_price" label="商品价格">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item prop="goods_number" label="商品数量">
              <el-input type="number" v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item prop="goods_weight" label="商品重量">
              <el-input type="number" v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item prop="goods_cat" label="商品分类">
              <!-- 级联选择器 -->
              <el-cascader
              :options="cateList"
              :props="addProps"
              v-model="addForm.goods_cat"
              @change="handleChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" :key="index" v-for="(item,index) in manyTabelData">
              <el-checkbox-group  v-model="item.attr_vals">
                <el-checkbox border :label="ch" :key="ci" v-for="(ch,ci) in item.attr_vals" ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="(item,index) in onlyTabelData" :key="index">
              <el-input v-model="item.attr_vals[0]"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片上传 action上传到服务器地址 -->
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="headersObj"
              :on-success="handleSuccess"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 v-model绑定到添加表单的商品介绍中 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addGoods" class="addBtn">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewVisible"
      @close="closeDialog"
      width="70%">
      <img :src="previewPath" class="previewImg" alt="">
    </el-dialog>
  </div>
</template>cateList
<script>
import _ from 'lodash'
export default {
  components: {},
  data() {
    return {
      // 记录步骤条的当前项
      activeIndex: '0',
      // 添加的表单数据
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        //  选择了的ID 需要一个数组来接收
        goods_cat: [],
        // 存在服务器中的图片地址
        pics: [],
        // 商品介绍
        goods_introduce: '',
        // 商品属性
        attrs: []
      },
      // 表单验证规则
      addFormRrules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      // 分类列表 默认设置为空
      cateList: [],
      // 级联选择器配置
      addProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        children: 'children',
        label: 'cat_name'
      },
      // 动态参数
      manyTabelData: [],
      // 静态属性
      onlyTabelData: [],
      // 上传图片的地址
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 设置图片上传的请求头对象
      headersObj: {
        // 设置Token
        Authorization: window.sessionStorage.getItem('token')
      },
      // 预览图片的URL 地址
      previewPath: '',
      // 控制预览图片对话框的出现或者消失
      previewVisible: false
    }
  },
  mounted() {
    // 获取所有的分类
    this.getCateList()
  },
  computed: {
    getID() {
      return this.addForm.goods_cat[2]
    }
  },
  methods: {
    // 获取所有的分类
    async getCateList() {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
      // this.total = res.data.total
      // console.log(this.cateList)
    },
    // 监听级联 选中的时候的改变
    handleChange() {
      // console.log(this.selectValue)
      // 判断是否选中了三级分类
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
        return
      }
      // 选的是三级分类
    },
    // 标签页面切换的事件 oldActiveName即将离开的文字，activeName即将进入
    beforeLeave(activeName, oldActiveName) {
      // console.log(oldActiveName)
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    // 根据选择了不同ID切换不同的面板
    async tableClicked() {
      // 判断是否来到了第二页的面板 动态参数面板
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(`/categories/${this.getID}/attributes`, {
          params: { sel: 'many' }
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        res.data.forEach(item => {
          item.attr_vals = (item.attr_vals.length !== 0) ? item.attr_vals.split(',') : []
        })
        this.manyTabelData = res.data
        // console.log(this.manyTabelData)
      } else if (this.activeIndex === '2') { // 判断是否来到了第三页的面板 静态属性面板
        const { data: res } = await this.$http.get(`/categories/${this.getID}/attributes`, {
          params: { sel: 'only' }
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        res.data.forEach(item => {
          item.attr_vals = (item.attr_vals.length !== 0) ? item.attr_vals.split(',') : []
        })
        this.onlyTabelData = res.data
        // console.log(this.onlyTabelData)
      }
    },
    // 处理图片预览事件
    handlePreview(file) {
      this.previewPath = file.response.data.url
      this.previewVisible = true
    },
    closeDialog() {
      // 关闭对话框
      // 清空预览图
      this.previewPath = ''
      // console.log(11111111)
    },
    // 处理删除图片事件
    handleRemove(file) {
      const pic_path = file.response.data.tmp_path
      const index = this.addForm.pics.findIndex(item => item.pic === pic_path)
      // console.log(index)
      this.addForm.pics.splice(index, 1)
      console.log(this.addForm.pics)
    },
    // 监听文件上传成功
    handleSuccess(response) {
      this.addForm.pics.push({ pic: response.data.tmp_path })
      // console.log(this.addForm)
    },
    // 发起请求进行添加商品
    addGoods() {
      this.$refs.addFormRef.validate(async val => {
        if (!val) return this.$message.error('请输入必要表单项')
        // 使用lodash深拷贝 之前的对象 因为之前 goods_cat双向绑定了表单
        // 等下处理goods_cat就报错 所以深拷贝一个对象出来
        const newForm = _.cloneDeep(this.addForm)
        newForm.goods_cat = newForm.goods_cat.join(',')
        // 处理动态参数
        this.manyTabelData.forEach(item => {
          const newObj = {
            'attr_id': item.attr_id,
            'attr_vals': item.attr_vals.join(',')
          }
          this.addForm.attrs.push(newObj)
        })
        // 处理静态属性
        this.onlyTabelData.forEach(item => {
          const newObj = {
            'attr_id': item.attr_id,
            'attr_vals': item.attr_vals.join(',')
          }
          this.addForm.attrs.push(newObj)
        })
        newForm.attrs = this.addForm.attrs
        // 发起请求
        const { data: res } = await this.$http.post('/goods', newForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.$router.push('/goods')
      })
    }
  }
}
</script>
<style lang="less" scoped>
.el-checkbox{
  margin: 0px 15px 0px 0px !important;
}
// 预览图片的大小
.previewImg{
  width: 100%;
}
.addBtn{
  margin-top: 20px;
}
</style>
